﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace AutoWrockTestable.Template
{
    public partial class TestableForm : Form
    {
        private readonly IEnumerable<string> data;

        public TestableForm(IEnumerable<string> data, string initialValue)
        {
            InitializeComponent();
            this.data = data;
            var autoData = new AutoCompleteStringCollection();
            autoData.AddRange(data.ToArray());
            classNameCombo.AutoCompleteCustomSource = autoData;
            classNameCombo.Text = initialValue;
            classNameCombo.Focus();
        }

        public string ClassName { get; private set; }

        private void OkButtonClick(object sender, EventArgs e)
        {
            ClassName = classNameCombo.Text;
            Dispose();
        }

        private void AutoCompleteTextChanged(object sender, EventArgs e)
        {
            if (classNameCombo.Text.Length >= 0 && classNameCombo.SelectedIndex == -1)
            {
                string text = classNameCombo.Text;
                if (!string.IsNullOrEmpty(text))
                {
                    var query = (from src in data
                                where src.ToLowerInvariant().Contains(text.ToLowerInvariant())
                                select src).Distinct().ToArray();

                    if (query.Any())
                    {
                        var cnt = classNameCombo.Items.Count;
                        var start = classNameCombo.SelectionStart;
                        classNameCombo.BeginUpdate();
                        classNameCombo.Items.Clear();
                        foreach (var s in query)
                            classNameCombo.Items.Add(s);
                        classNameCombo.EndUpdate();
                        if (cnt > query.Length)
                            classNameCombo.DroppedDown = false;
                        if(!classNameCombo.DroppedDown)
                        {
                            classNameCombo.DroppedDown = true;
                            Cursor.Current = Cursors.Default;
                        }
                        classNameCombo.SelectionStart = start;
                        classNameCombo.SelectionLength = classNameCombo.Text.Length-start;
                    }
                }
            }
        }
    }
}
